<template>
<el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" width="60%" top="3%">
    <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first"></el-tab-pane>
        <el-tab-pane label="规则说明" name="second"></el-tab-pane>
    </el-tabs>
    <el-form style="height:600px;overflow:auto;padding-right:40px" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '170px' : '150px'">
        <el-row v-if="activeName=='first'">
            <el-col :span="24">
                <el-form-item label="套票名称" prop="jointName">
                    <el-input v-model="dataForm.jointName"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="所属区域名称" prop="scenicId">
                    <el-select v-model="dataForm.scenicId" placeholder="所属区域" clearable>
                        <el-option v-for="item in scenicNameList" :key="item.id" :label="item.scenicName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="景区名称" prop="boundIdsArr">
                    <el-select v-model="dataForm.boundIdsArr" placeholder="景区名称" multiple clearable>
                        <el-option v-for="item in scenicSpotNameList" :key="item.spid" :label="item.scenicName" :value="item.spid">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="出发港口" prop="startPortName">
                    <el-select style="width: 100%" v-model="dataForm.startPortName" placeholder="出发港口" clearable>
                        <el-option v-for="(item, index) in startOptions" :key="index" :value="item" :label="item">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="到达港口" prop="endPortName">
                    <el-select style="width: 100%" v-model="dataForm.endPortName" placeholder="到达港口" clearable>
                        <el-option v-for="(item, index) in endOptions" :key="index" :value="item.endPortName" :label="item.endPortName">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="封面" prop="coverImage">
                    <el-upload class="avatar-uploader" :action="url" :show-file-list="false" :on-success="(res, file, fileList)=>successHandle1(res, file, fileList)" :before-upload="beforeUploadHandle">
                        <img v-if="dataForm.coverImage" :src="dataForm.coverImage" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

            </el-col>
            <!-- <el-col :span="24">
                <el-form-item label="详情轮播图(最多10张)" prop="">
                    <el-upload :action="url" :file-list="fileList2" :limit="10" :on-preview="handlePictureCardPreview" :before-upload="beforeUploadHandle" list-type="picture-card" :on-success="successHandle2" :on-remove="handleRemove2">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
            </el-col> -->
        </el-row>
        <template v-else>
            <editor-vue :content="dataForm.reserveNotice" @EditorChange="getEditor" ref="infoIntroduceRef"></editor-vue>
        </template>
    </el-form>

    <template slot="footer">
        <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
</el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import editorVue from '@/components/editor'
export default {
    data() {
        return {
            url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
            fileList2: [],
            dialogImageUrl: '',
            dialogVisible: false,
            visible: false,
            activeName: "first",
            dataForm: {
                id: "",
                homestayId: this.$store.state.user.homestayId,
                endPortName: "", //停靠港Name
                endPortNo: 0, //停靠港NO
                jointName: "",
                scenicId: '', //区域id
                boundIds: "", //景区id
                boundIdsArr: [],
                startPortName: "", //起始港name
                startPortNo: 0, //起始港NO
                type: 7,
                reserveNotice: '',
                tpDetails: '',
            },
            romTypes: [],
            startOptions: [],
            endOptions: [],
            scenicNameList: [], //所属区域list
            scenicSpotNameList: [], //景区名称list
            placeInfo: null
        };
    },
    computed: {
        dataRule() {
            return {
                jointName: [{
                    required: true,
                    message: this.$t("validate.required"),
                    trigger: "blur",
                }, ],
                startPortName: [{
                    required: true,
                    message: this.$t("validate.required"),
                    trigger: "blur",
                }, ],
                endPortName: [{
                    required: true,
                    message: this.$t("validate.required"),
                    trigger: "blur",
                }, ],
            };
        },
    },
    components: {
        editorVue
    },
    watch: {
        "activeName"(newval, oldval) {
            if (newval == 'second') {
                this.$nextTick(() => {
                    this.$refs.infoIntroduceRef.init()
                })
            }
        },
        'dataForm.startPortName'(newval, oldval) {
            let ind = this.startOptions.findIndex((item) => item == newval);
            this.endOptions = this.placeInfo[newval];
        },
        "dataForm.scenicId"(newval, oldval) {
            if (newval != oldval) {
                this.getScenicSpotNameList(newval);
            }
        }
    },
    created() {},
    methods: {
        getEditor(val) {
            this.dataForm.reserveNotice = val;
        },
        // 上传之前
        beforeUploadHandle(file) {
            if (
                file.type !== "image/jpg" &&
                file.type !== "image/jpeg" &&
                file.type !== "image/png" &&
                file.type !== "image/gif"
            ) {
                this.$message.error(this.$t("upload.tip", {
                    format: "jpg、png、gif"
                }));
                return false;
            }
        },
        // 上传成功
        successHandle1(res, file, fileList) {
            if (res.code !== 0) {
                return this.$message.error(res.msg);
            }
            this.dataForm.coverImage = res.data.url;
        },
        getScenicName() {
            this.$http.get('/scenic/isscenic/selectScenicList').then(res => {
                this.scenicNameList = res.data.data;
            })
        },
        getScenicSpotNameList(id) {
            console.log(id)
            this.$http.get('/scenic/isscenicspot/selectScenicList/' + id).then(res => {
                this.scenicSpotNameList = res.data.data
            })
        },
        //港口
        queryOption() {
            this.$http
                .get("/travel/isshipportline/api/shipHotelList")
                .then(({
                    data: res
                }) => {
                    this.placeInfo = res.data;
                    for (let p in this.placeInfo) {
                        this.startOptions = [...this.startOptions, p];
                    }
                    if (this.dataForm.startPortName == '') {
                        this.endOptions = this.placeInfo[this.startOptions[0]];
                    } else {
                        let index = this.startOptions.findIndex((item) => item == this.dataForm.startPortName);
                        this.endOptions = this.placeInfo[this.startOptions[index]]
                    }

                });
        },
        init() {
            this.visible = true;
            this.getScenicName();
            this.$nextTick(() => {
                this.dataForm.boundIdsArr = [];
                this.fileList2 = [];
                this.dataForm.reserveNotice = '';
                this.dataForm.tpDetails = '';
                this.activeName = "first";
                this.$refs["dataForm"].resetFields();
                if (this.dataForm.id) {
                    this.getInfo();
                } else {
                    this.queryOption();
                }
            });
        },
        // 获取信息
        getInfo() {
            this.$http
                .get("/scenic/ticket/package/" + this.dataForm.id)
                .then(({
                    data: res
                }) => {
                    this.fileList2 = [];
                    if (res.code !== 0) {
                        return this.$message.error(res.msg);
                    }
                    this.dataForm = {
                        ...this.dataForm,
                        ...res.data,
                    };
                    let imgArr = this.dataForm.tpDetails.split(",");

                    imgArr.filter((item) => {
                        this.fileList2.push({
                            url: item
                        })
                    })
                    this.dataForm.boundIdsArr = this.dataForm.boundIds.split(",");
                    this.queryOption();
                })
                .catch(() => {});
        },
        // 表单提交
        dataFormSubmitHandle: debounce(
            function () {
                this.$refs["dataForm"].validate((valid) => {
                    if (!valid) {
                        return false;
                    }
                    let startPort = this.endOptions.filter(
                        (item) => item.startPortName == this.dataForm.startPortName
                    );
                    if (startPort) {
                        this.dataForm.startPortNo = startPort[0].startPortNum;
                        this.dataForm.endPortNo = startPort[0].endPortNum;
                    }

                    this.dataForm.boundIds = this.dataForm.boundIdsArr.join(",");
                    let tpDetailsArr = [];
                    this.fileList2.filter((item) => {
                        tpDetailsArr.push(
                            item.url
                        )
                    })
                    this.dataForm.tpDetails = tpDetailsArr.join(',');
                    this.$http[!this.dataForm.id ? "post" : "put"](
                            "/scenic/ticket/package",
                            this.dataForm
                        )
                        .then(({
                            data: res
                        }) => {
                            if (res.code !== 0) {
                                return this.$message.error(res.msg);
                            }
                            this.$message({
                                message: this.$t("prompt.success"),
                                type: "success",
                                duration: 500,
                                onClose: () => {
                                    this.visible = false;
                                    this.$emit("refreshDataList");
                                },
                            });
                        })
                        .catch(() => {});
                });
            },
            1000, {
                leading: true,
                trailing: false
            }
        ),
    },
};
</script>

<style lang="scss" scoped>
h3 {
    padding: 30px 0 15px;
    width: 94%;
    margin: 0 auto 30px;
    border-bottom: 1px solid #ddd;
    color: #303133;
    font-size: 22px;
    overflow: hidden;
}

.rooms .item {
    display: inline-block;
    margin-right: 15px;
    position: relative;

    .el-icon-error {
        position: absolute;
        right: 6px;
        top: -6px;
        font-size: 20px;
        color: #dd0606;
    }
}
</style>
